//
//  HJPasswordCodeView.m
//  KaiChat
//
//  Created by lx on 2023/10/17.
//

#import "HJPasswordCodeView.h"

 
@interface HJInputItem: UIControl

@property(nonatomic,getter=isSecureTextEntry) BOOL secureTextEntry;       // default is NO
@property (nonatomic, copy) NSString *text;

@end


@implementation HJInputItem {
    UILabel __weak *_textLabel;
    UIView __weak *_secureTextEntryView;
}

- (void)setSelected:(BOOL)selected {
    [super setSelected:selected];
    
    if (selected) {
        self.layer.borderColor = UIColor.tj_mainColor.CGColor;
        self.layer.borderWidth = 1;
    } else {
        self.layer.borderColor = UIColor.tj_F6F6F6Color.CGColor;
        self.layer.borderWidth = 0;
    }
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
     
        self.userInteractionEnabled = NO;
        self.addCornerRadius(10);

        UILabel *textLabel = [UILabel lableWithSuperView:self font:UIFontMediumMake(20) color:UIColor.tj_1A1A1AColor title:nil textAlignment:NSTextAlignmentCenter];
        
        UIView *secureTextEntryView = [UIView addToView:self];
        secureTextEntryView.backgroundColor = UIColor.blackColor;
        secureTextEntryView.layer.cornerRadius = 7;
        secureTextEntryView.layer.masksToBounds = YES;
        
        _textLabel = textLabel;
        _secureTextEntryView = secureTextEntryView;
        
        [self setText:nil];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGSize size = CGSizeMake(14, 14);
    _textLabel.frame = self.bounds;
    _secureTextEntryView.frame = CGRectMake((self.frame.size.width - size.width) * 0.5, (self.frame.size.height - size.height) * 0.5, size.width, size.height);
}

- (void)setText:(NSString *)text {
    _text = text;
    
    _textLabel.text = text;
    
    if (text) {
        _textLabel.hidden = _secureTextEntry;
        _secureTextEntryView.hidden = !_secureTextEntry;
    } else {
        _textLabel.hidden = NO;
        _secureTextEntryView.hidden = YES;
    }
}
 

@end


@interface HJPasswordCodeView ()

@property (nonatomic, assign) NSInteger itemCount;
@property (nonatomic, assign) CGFloat itemMargin;
@property (nonatomic, weak) UIControl *maskView;
@property (nonatomic, strong) NSMutableArray<HJInputItem *> *inputItems;
@property (nonatomic, weak) UIView *cursorView;

@end

@implementation HJPasswordCodeView


- (instancetype)initWithCount:(NSInteger)count margin:(CGFloat)margin {
    if (self = [super init]) {
        self.itemCount = count;
        self.itemMargin = margin;
        [self setSubView];
    }
    return self;
}

- (void)setSubView {
    
    self.backgroundColor = [UIColor clearColor];
    
    self.inputItems = @[].mutableCopy;
    
    UITextField *textField = [UITextField addToView:self];
    textField.keyboardType = UIKeyboardTypeNumberPad;
    textField.hidden = YES;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _textField = textField;

    UIButton *maskView = [UIButton addToView:self];
    maskView.backgroundColor = self.backgroundColor;
    [maskView addTarget:self action:@selector(didClickMaskView) forControlEvents:(UIControlEventTouchUpInside)];
    self.maskView = maskView;


    for (NSInteger i = 0; i < self.itemCount; i++) {
        HJInputItem *inputItem = [[HJInputItem alloc] init];
        inputItem.secureTextEntry = _secureTextEntry;
        inputItem.backgroundColor = UIColor.tj_F6F6F6Color;
        [self addSubview:inputItem];
        [self.inputItems addObject:inputItem];
    }
}
 
-(void)addCursorAnimation{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    animation.fromValue = [NSNumber numberWithFloat:1.0f];
    animation.toValue = [NSNumber numberWithFloat:0.0f];//这是透明度。
    animation.autoreverses = YES;
    animation.duration = 0.5;
    animation.repeatCount = MAXFLOAT;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    [self.cursorView.layer addAnimation:animation forKey:nil];
}
 
- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (self.inputItems.count != self.itemCount) return;
    
    CGFloat temp = self.bounds.size.width - (self.itemMargin * (self.itemCount - 1));
    CGFloat w = temp / self.itemCount;
    CGFloat x = 0;
    
    for (NSInteger i = 0; i < self.inputItems.count; i++) {
        x = i * (w + self.itemMargin);
        
        HJInputItem *inputItem = self.inputItems[i];
        inputItem.frame = CGRectMake(x, (self.frame.size.height - w) * 0.5, w, w);
        inputItem.secureTextEntry = _secureTextEntry;
    }
    
    HJInputItem *currentInputItem = self.inputItems[self.textField.text.length];
    self.cursorView.center = currentInputItem.center;

    
    self.textField.frame = self.bounds;
    self.maskView.frame = self.bounds;
}

- (void)textFieldDidChange:(UITextField *)textField {
    
    if (textField.text.length > self.itemCount) {
        textField.text = [textField.text substringWithRange:NSMakeRange(0, self.itemCount)];
        return;//不再回调,防止输入过快导致多次请求接口
    }
    
    for (int i = 0; i < self.itemCount; i++) {
        HJInputItem *inputItem = [self.inputItems objectAtIndex:i];
        if (i < textField.text.length) {
            inputItem.text = [textField.text substringWithRange:NSMakeRange(i, 1)];
            inputItem.selected = YES;
        } else {
            inputItem.text = nil;
            inputItem.selected = NO;
        }
    }
    
    if (textField.text.length < self.itemCount) {
        self.cursorView.hidden = NO;
        HJInputItem *currentInputItem = self.inputItems[textField.text.length];
        self.cursorView.center = currentInputItem.center;
    } else {
        self.cursorView.hidden = YES;
    }

    if ([self.delegate respondsToSelector:@selector(textDidChange:text:)]) {
        [self.delegate textDidChange:self text:textField.text];
    }
}

- (void)reset {
    [self.inputItems enumerateObjectsUsingBlock:^(HJInputItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.text = nil;
    }];
    self.textField.text = nil;
    [self.textField becomeFirstResponder];
    [self textFieldDidChange:self.textField];
}
 
- (void)didClickMaskView {
    [self.textField becomeFirstResponder];
}

- (BOOL)endEditing:(BOOL)force {
    [self.textField endEditing:force];
    return [super endEditing:force];
}

- (void)dealloc {
    [self.cursorView.layer removeAllAnimations];
}

@end
